<template>
  <div class="classify-container">
    <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
      <!-- 表格区域 -->
      <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
        <template #header>
          <div class="flex items-center justify-between">
            <p>分类管理</p>
            <ElButton type="primary" size="small" @click="openAddDialog">添加</ElButton>
          </div>
        </template>

        <!-- 懒加载的树形表格 -->
        <div class="h-[calc(100%-50px)]">
          <ElTable
            :data="categoryList"
            height="360px"
            border
            class="sm:h-full"
            row-key="id"
            lazy
            :load="fetchChildCategories"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <ElTableColumn prop="categoryName" label="分类名称" />
            <ElTableColumn prop="orderNum" label="排序" />
            <ElTableColumn prop="status" label="状态" #default="scope">
              {{ scope.row.status == 1 ? '正常' : '停用' }}
            </ElTableColumn>
            <ElTableColumn prop="createTime" label="创建时间" />
            <ElTableColumn label="操作" align="center" width="300" #default="scope">
              <div class="flex-center justify-center gap-8px">
                <ElButton type="primary" plain size="small" @click="openAddChildDialog(scope.row)">添加子目录</ElButton>
                <ElButton type="warning" plain size="small" @click="openEditDialog(scope.row)">编辑</ElButton>
                <ElPopconfirm title="确定要删除该分类吗？" @confirm="deleteCategory(scope.row)">
                  <template #reference>
                    <ElButton type="danger" plain size="small">删除</ElButton>
                  </template>
                </ElPopconfirm>
              </div>
            </ElTableColumn>
          </ElTable>
        </div>
      </ElCard>
    </div>

    <!-- 对话框 -->
    <div>
      <ElDialog v-model="dialogVisible" :title="dialogTitle" width="30%" destroy-on-close append-to-body>
        <ElForm label-width="120px">
          <ElFormItem label="分类名称">
            <ElInput v-model="categoryForm.categoryName" />
          </ElFormItem>
          <ElFormItem v-if="!categoryForm.hasChildren" label="上级部门" prop="categoryId">
            <ElTreeSelect
              clearable
              v-model="categoryForm.categoryId"
              :data="categoryOptions"
              :props="{ value: 'id', label: 'name', isLeaf: 'leaf' }"
              :load="loadCategoryNodes"
              lazy
              @visible-change="handleTreeSelectVisibleChange"
              value-key="id"
              placeholder="选择上级部门"
              check-strictly
            />
          </ElFormItem>
          <ElFormItem label="排序">
            <ElInputNumber v-model="categoryForm.orderNum" :min="0" :max="100" />
          </ElFormItem>
          <ElFormItem label="状态">
            <ElRadioGroup v-model="categoryForm.status">
              <ElRadio :label="1">正常</ElRadio>
              <ElRadio :label="0">停用</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="submitCategory">提交</ElButton>
            <ElButton @click="dialogVisible = false">取消</ElButton>
          </ElFormItem>
        </ElForm>
      </ElDialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { PictureById, findAll, SavePicture, UpdatePicture, RemovePicture } from '@/service/api/material/classify';

// 数据定义
const categoryList = ref([]); // 分类列表
const categoryOptions = ref([]); // 树形选择器选项
const dialogVisible = ref(false); // 对话框显示状态
const dialogTitle = ref(''); // 对话框标题
const categoryForm = ref({
  id: null,
  categoryName: '',
  categoryId: null,
  status: 1,
  orderNum: 1,
  hasChildren: false,
}); // 表单数据
const isTreeDataLoaded = ref(false); // 是否已加载树形数据

// 生命周期钩子
onMounted(() => {
  fetchCategoryList();
});

onBeforeUnmount(() => {
  categoryList.value = [];
  categoryOptions.value = [];
  isTreeDataLoaded.value = false;
  dialogVisible.value = false;
});

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const { data } = await findAll();
    categoryList.value = data;
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('加载分类列表失败');
  }
};

// 加载子分类
const fetchChildCategories = async (row, treeNode, resolve) => {
  try {
    const { data } = await PictureById(row.id);
    resolve(data || []);
  } catch (error) {
    console.error('加载子分类失败:', error);
    resolve([]);
  }
};

// 树形选择器显示时加载根节点
const handleTreeSelectVisibleChange = async (visible) => {
  if (visible && !isTreeDataLoaded.value) {
    await loadRootCategories();
  }
};

// 加载根分类
const loadRootCategories = async () => {
  try {
    const res = await PictureById(0);
    categoryOptions.value = res.data.map(item => ({
      id: item.id,
      name: item.categoryName,
      leaf: !item.hasChildren,
    }));
    isTreeDataLoaded.value = true;
  } catch (error) {
    console.error('加载根分类失败:', error);
  }
};

// 懒加载树形选择器节点
const loadCategoryNodes = async (node, resolve) => {
  if (node.level === 0) {
    return resolve(categoryOptions.value);
  }
  try {
    const parentId = node.data.id;
    const res = await PictureById(parentId);
    const nodes = res.data.map(item => ({
      id: item.id,
      name: item.categoryName,
      leaf: !item.hasChildren,
    }));
    resolve(nodes);
  } catch (error) {
    console.error('加载子节点失败:', error);
    resolve([]);
  }
};

// 打开添加顶级分类对话框
const openAddDialog = () => {
  categoryForm.value = {
    id: null,
    categoryName: '',
    categoryId: null,
    status: 1,
    orderNum: 1,
    hasChildren: false,
  };
  dialogTitle.value = '添加';
  dialogVisible.value = true;
};

// 打开添加子分类对话框
const openAddChildDialog = async (parentRow) => {
  await loadRootCategories(); // 确保选项已加载
  categoryForm.value = {
    id: null,
    categoryName: '',
    categoryId: parentRow.id,
    status: 1,
    orderNum: 1,
    hasChildren: false,
  };
  dialogTitle.value = '添加子目录';
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = async (row) => {
  await loadRootCategories(); // 确保选项已加载
  categoryForm.value = { ...row };
  if (categoryForm.value.categoryId === 0) {
    categoryForm.value.categoryId = null; // 假设0表示无上级分类
  }
  dialogTitle.value = '编辑';
  dialogVisible.value = true;
};

// 提交分类数据
const submitCategory = async () => {
  try {
    const formData = { ...categoryForm.value };
    if (formData.categoryId === null) {
      formData.categoryId = 0; // 假设0表示顶级分类
    }
    let result;
    if (!formData.id) {
      result = await SavePicture(formData);
    } else {
      result = await UpdatePicture(formData);
    }
    if (result.response.data.code === '0000') {
      dialogVisible.value = false;
      ElMessage.success('操作成功');
      await fetchCategoryList();
    } else {
      ElMessage.error(result.response.data.message || '操作失败');
    }
  } catch (error) {
    console.error('提交分类失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
};

// 删除分类
const deleteCategory = async (row) => {
  try {
    const result = await RemovePicture(row.id);
    if (result.response.data.code === '0000') {
      ElMessage.success('删除成功');
      await fetchCategoryList();
    } else {
      ElMessage.error(result.response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除分类失败:', error);
    ElMessage.error('删除失败，请稍后重试');
  }
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
</style>